import React, {useEffect, useState} from 'react';
import {Demand} from './data.d';
import {modulesUrl} from "@/assets/constant/modulesUrl";
import {breadcrumbItemRender, handleSave} from "@/assets/components/tableList";
import {createEditor, hooksSet, uuid} from "@/assets/utils/utils";
import {get, listForSelect, save} from "@/assets/service/baseService";
import {useRequest} from 'umi';
import {Button, Card, Form, InputNumber, Select, Space} from "antd";
import {ProFormText} from "@ant-design/pro-form";
import {PageContainer} from "@ant-design/pro-layout";
import {history} from "@@/core/history";
import E from 'wangeditor'
import {DemandType} from "@/pages/demand/DemandTypeList/data";
import Upload from "@/assets/components/upload";

const DemandEdit: React.FC<{}> = (props) => {
  /**
   * type：0、全部需求  1、待办需求  2、流转中需求   3、已完成需求
   */
    // @ts-ignore
  const type = props.match.params.type;
  /**
   * 上一个页面
   */
  const prev = '/demand/demand/' + type;
  /**
   * demandId为0，说明是新建
   */
    // @ts-ignore
  const demandId = props.match.params.id;

  const [form] = Form.useForm();

  let editor: E;

  /**
   * 原文件ids
   */
  const [annexIds, setAnnexIds] = useState<string>()
  /**
   * 需求类型提示
   */
  const [typeTips, setTypeTips] = useState<any>("")
  /**
   * 获取需求类型
   */
  const getDemandTypeRun = useRequest((id: string) => get(modulesUrl.demandDemandType, id), {
    manual: true,
    onSuccess: (result: DemandType, params) => {
      form.setFieldsValue({estimateWorkingHours: result.estimateWorkingHours})
      // 设置类型提示
      hooksSet(setTypeTips, result.description)
    }
  }).run
  /**
   * 获取需求
   */
  const [demand, setDemand] = useState<Demand>();
  const getDemandRun = useRequest((id: string, editor: any) => get(modulesUrl.demandDemand, id), {
    manual: true,
    onSuccess: (result: Demand, params) => {
      hooksSet(setDemand, result)
      form.setFieldsValue(result)
      form.setFieldsValue({"type.id": result.type?.id, "annexIds": result.annexIds})
      // 获取需求类型
      getDemandTypeRun(result.type?.id || "")
      // 获取原附件列表
      hooksSet(setAnnexIds, result.annexIds)
      params[1].txt.append(result.description || "")
    }
  }).run
  /**
   * 获取需求类型列表
   */
  const [demandTypeSelectList, setDemandTypeSelectList] = useState([])
  const getDemandTypeSelectListRun = useRequest(() => listForSelect(modulesUrl.demandDemandType), {
    manual: true,
    onSuccess: (result, params) => {
      hooksSet(setDemandTypeSelectList, result);
    }
  }).run

  /**
   * 实时保存
   */
  const realTimeSave = async () => {
    await form.validateFields().then(async () => {
      await save(modulesUrl.demandDemand, form.getFieldsValue());
      return true;
    }).catch(async (errorInfo) => {
      if (errorInfo.errorFields.length === 0) {
        await save(modulesUrl.demandDemand, form.getFieldsValue());
      }
    })
  }


  /**
   * 启动加载
   */
  useEffect(() => {
    // 获取需求类型
    getDemandTypeSelectListRun()
    // 创建富文本框
    editor = createEditor("descriptionEditor", async (newHtml: string) => {
      form.setFieldsValue({"description": newHtml})
      await realTimeSave()
    })
    // 如果是编辑，则获取需求实体
    if (demandId !== "0") {
      getDemandRun(demandId, editor)
    }
    return () => {
      // 组件销毁时销毁编辑器  注：class写法需要在componentWillUnmount中调用
      editor && editor.destroy()
    }
  }, []);

  return (
    <PageContainer
      title={(demandId !== "0" ? "编辑" : "新建") + "需求"}
      header={{
        breadcrumb: {
          routes: [
            {
              path: prev,
              breadcrumbName: '需求列表',
            },
            {
              path: '',
              breadcrumbName: (demandId !== "0" ? "编辑" : "新建") + '需求',
            }
          ],
          itemRender: breadcrumbItemRender
        }
      }}
    >
      <Card bordered={false}>
        <Form
          layout={"vertical"}
          form={form}
          preserve={false}
          onValuesChange={realTimeSave}
        >
          <ProFormText key="name" name="name" label="名称" placeholder="请输入名称"
                       rules={[{required: true, message: '名称为必填项',}]}
                       disabled={demandId === "0" || demand?.status === "1" ? false : true}/>
          <Form.Item key={"typeId"} name={"typeId"} label={"需求类型"}
                     rules={[{required: true, message: '需求类型为必选项',}]} extra={typeTips}>
            <Select showSearch placeholder={"请选择需求类型"} optionFilterProp={"label"} options={demandTypeSelectList}
                    onSelect={(value: string) => getDemandTypeRun(value)}
                    disabled={demandId === "0" || demand?.status === "1" ? false : true}/>
          </Form.Item>
          <Form.Item key="estimateWorkingHours" name="estimateWorkingHours" label="预估工时（小时）"
                     rules={[{required: true, message: '预估工时为必填项',}]}>
            <InputNumber placeholder="选择需求类型后，自动写入" style={{width: "100%"}}
                         disabled={true}/>
          </Form.Item>
          <Form.Item key="annexUpload" name="annexUpload" label="上传附件" style={{width: "300px"}}>
            <Upload form={form} initIds={annexIds}/>
          </Form.Item>
          <Form.Item key="description" name="description" label="需求说明" rules={[{required: true, message: '需求说明为必填项',}]}>
            <div id="descriptionEditor" style={{zIndex: 0, position: 'relative'}}></div>
          </Form.Item>
          <Form.Item style={{textAlign: "right"}}>
            <Space>
              <Button onClick={() => history.push(prev)}>
                取消
              </Button>
              <Button type="primary"
                      onClick={() => handleSave(form, modulesUrl.demandDemand, null, null, () => {
                        history.push(prev)
                      })}>
                {demandId === "0" || demand?.status === "1" ? "保存草稿" : "更新"}
              </Button>
              {demandId === "0" || demand?.status === "1" ? <Button type="primary" onClick={() => {
                form.setFieldsValue({"isIssue": "1"});
                handleSave(form, modulesUrl.demandDemand, null, null, () => history.push(prev))
              }}>
                提交需求
              </Button> : undefined}
            </Space>
          </Form.Item>
          <Form.Item initialValue={demandId !== "0" ? demandId : uuid(32)} key="id" name="id"
                     className={"formItemHidden"}></Form.Item>
          <Form.Item initialValue={demandId !== "0" ? false : true} key="newRecord" name="newRecord"></Form.Item>
          <Form.Item key="annexIds" name="annexIds" className={"formItemHidden"}></Form.Item>
          <Form.Item key="isIssue" name="isIssue" className={"formItemHidden"} initialValue={"0"}></Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};
export default DemandEdit;
